package client;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.security.cert.X509Certificate;

import util.Record;
import util.SSLClientServer;

public class Client extends SSLClientServer {
	private BufferedReader userInput;
	

	public Client(int port, String host) {
		super(port, host);
		userInput = new BufferedReader(new InputStreamReader(System.in));
	
		// TODO Auto-generated constructor stub
	}
	
	/**
	 * User login. Call this before connect to ensure the correct keystores is used.
	 */
	public void login(){
		try {
			System.out.print("Login: ");
			String user = userInput.readLine();
			String passwd;

			if(System.console() != null && (passwd = new String(System.console().readPassword("Password: "))) != null);
			else {
				System.out.print("Echoed password: ");
				passwd = userInput.readLine();
			}
			
			setUpKeyManager("ClientKeystore/"+user+".jks", passwd);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
	}
	
	/**
	 * Connects to server and sets up input/output over socket.
	 */
	public void connect() {
		try {
			SSLSocketFactory factory = ctx.getSocketFactory();
			socket = (SSLSocket) factory.createSocket(host, port);
			System.out.println("Handshaking");
			socket.startHandshake();
			System.out.println("Handshake succsessfull");
			out = new PrintWriter(new BufferedWriter(
					new OutputStreamWriter(socket.getOutputStream())));
			if (out.checkError())
				System.out
						.println("SSLSocketClient: java.io.PrintWriter error");
			socketInput = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));				

		} catch (Exception e) {
			e.printStackTrace();
			System.exit(0);
			// TODO Auto-generated catch block
			
		}
	}
	
	/**
	 * Should be called before exiting program. 
	 */
	public void cleanUp(){
		super.cleanUp();
		try {
			userInput.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * Starts a user session based on the keystore used in login.
	 */
	public void startUserSession(){
		try {
			boolean done = false;	
			System.out.println("Welcome!");
			
			while (!done){	
				printAlternativs();
				int choice = Integer.parseInt(userInput.readLine());
				
				switch(choice){
					case(1):
						out.println(choice + ":" + getRecordNbr());
						out.flush();
						break;
					case(2):
						out.println(choice + ":" + getpNbr());
						out.flush();
						break;
					case(3):
						//out.println(choice + ":" + getRecordNbr());
						//out.flush();
						System.out.println("TO TEDIOUS TO IMPLEMENT.");
						continue;
					case(4):
						out.println(choice + ":" + getRecordNbr());
						out.flush();
						break;
					case(5):
						out.println(choice + ":" + createRecord());
						out.flush();
						break;
				}
				
				String response  = socketInput.readLine();
				if(response.contains("ENDSESSION")){
					done = true;
				}
				while(!response.equals("END")){
					System.out.println(response);
					response = socketInput.readLine();
					
				}
				
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private String getpNbr() throws IOException {
		System.out.println("Enter person number(xxxxxx-xxxx):");		
		return userInput.readLine();
	}

	private String getRecordNbr() throws IOException {
		System.out.println("Enter record number:");		
		return userInput.readLine();
	}
	
	

	private void printAlternativs(){	
		System.out.println("1. Get record by given record number");
		System.out.println("2. List all record by given person number");
		System.out.println("3. Write to record by record number");
		System.out.println("4. Delete record by record number");
		System.out.println("5. Create new record");
		
	}
	
	private String createRecord() throws IOException{
		System.out.println("Person number of patient:");		
		String patientPnbr = userInput.readLine();
		
		System.out.println("Person number of nurse:");
		String nurse = userInput.readLine();
		
		System.out.println("Data");
		String data = userInput.readLine();
		
		return patientPnbr +  ":" + 
					nurse + ":" + data;
		
		
		
	}

}
